package sardine;

import sardine.mvc.ModelAndView;
import sardine.mvc.TemplateEngine;
import sardine.mvc.TemplateViewRoute;

import java.util.Map;

/**
 * @auth bruce-sha
 * @date 2015/5/21
 */
public abstract class SimpleTemplateViewRoute extends SimpleRoute {

    protected SimpleTemplateViewRoute(final String path, final String acceptType) {
        super(path, acceptType);
    }

    @Override
    public String render(Object object) {
        ModelAndView modelAndView = (ModelAndView) object;
        return render(modelAndView);
    }

    public ModelAndView modelAndView(Map<String, Object> model, String viewName) {
        return new ModelAndView(model, viewName);
    }

    public abstract String render(ModelAndView modelAndView);


    public static SimpleTemplateViewRoute create(String path,
                                                 TemplateViewRoute route,
                                                 TemplateEngine engine) {
        return create(path, SardineBase.DEFAULT_ACCEPT_TYPE, route, engine);
    }

    public static SimpleTemplateViewRoute create(String path,
                                                 String acceptType,
                                                 TemplateViewRoute route,
                                                 TemplateEngine engine) {
        return new SimpleTemplateViewRoute(path, acceptType) {

            @Override
            public Object apply(Request request, Response response) throws Exception {
                return route.apply(request, response);
            }

            @Override
            public String render(ModelAndView modelAndView) {
                return engine.render(modelAndView);
            }
        };
    }


}